package com.erp.service;

import com.erp.bean.User;
import com.erp.dao.UserDao;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @Author tj
 * @Date 2022-04-20 15:59:16
 */
public class UserService {
    UserDao userDao = new UserDao();

    /* *
     * @author tj
     * @name 登录
     * @time 15:59 2022/4/20
     * @param username: 账号
     * @param password: 密码
     **/
    public void login(String username, String password, HttpServletRequest request) throws Exception {
        // 实现登录逻辑
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new Exception("用户名或密码不能为空");
        }
        User user = userDao.getUserByUsername(username);
        // 用户是否存在
        if (user == null) {
            throw new Exception("用户不存在");
        }
        // 密码是否正确
        if (!user.getPassword().equals(password)) {
            throw new Exception("密码错误");
        }
        // 设置用户session
        HttpSession session = request.getSession();
        // 登录标识符
        session.setAttribute("isLogin", true);
        // 存入用户信息
        session.setAttribute("user", user);
        // 存入登录时间
        session.setAttribute("time", System.currentTimeMillis());

    }

    /* *
     * @author tj
     * @name 保存用户
     * @time 16:07 2022/5/25
     * @param user:
     **/
    public void saveUser(User user) throws Exception {
        // 1.查询用户是否存在
        User muser = userDao.getUserByUsername(user.getUsername());
        if(!ObjectUtils.isEmpty(muser)){
            //1.抛出异常，用户名已存在
            throw new Exception("用户名已存在");
        }
        // 2.保存用户
        // todo
        boolean ret = userDao.saveUser(user);
        if(!ret){
            throw new Exception("保存失败！");
        }

    }

    public void deleteById(Integer id) throws Exception {
        boolean ret = userDao.deleteById(id);
        if(!ret){
            throw new Exception("删除失败！");
        }
    }

    public void editUser(User user) throws Exception {
        User muser = userDao.getUserByUsername(user.getUsername());
        if(!ObjectUtils.isEmpty(muser)){
            //1.抛出异常，用户名已存在
            throw new Exception("用户名已存在");
        }
        boolean ret = userDao.editUser(user);
        if(!ret){
            throw new Exception("修改失败！");

        }
    }

    public User getUserByUserName(String username) throws Exception {
        User muser = userDao.getUserByUsername(username);
        if(ObjectUtils.isEmpty(muser)){
            throw new Exception("用户不存在！");
        }
        return muser;
    }
}